/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
    // 1.立即执行
    // 2.异常处理
    constructor(executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (e) {
            this.reject(e)
        }
    }

    status = PENDING
    value = undefined
    reason = undefined
    // then可以被多次调用，因此存储回调函数的变量为数组
    successCallback = []
    failCallback = []

    // 1.判断当前状态是否为等待，是则阻止向下执行
    // 2.保存状态和value/reason
    // 3.如果有回调函数存在，则循环调用
    resolve = value => {
        if (this.status !== PENDING) return
        this.status = FULFILLED
        this.value = value
        while (this.successCallback.length !== 0) this.successCallback.shift()()
    }

    reject = reason => {
        if (this.status !== PENDING) return
        this.status = REJECTED
        this.reason = reason
        while (this.failCallback.length !== 0) this.failCallback.shift()()
    }

    // 1.then可以被链式调用，因此返回Promise对象
    // 2.then可以不传参，相当于then(value => value)
    // 3.回调函数返回Promise对象/普通值，需要对类型进行判断
    // 4.判断Promise自返回的情况
    // 5.如果状态为pending则存储回调函数
    // 6.异常情况处理，push进数组的回调函数也需要包一层异常处理
    then(successCallback, failCallback) {
        successCallback = successCallback ? successCallback : value => value
        failCallback = failCallback ? failCallback : reason => { throw reason }
        let promise2 = new MyPromise((resolve, reject) => {
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    try {
                        let x = successCallback(this.value)
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                }, 0)
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let x = failCallback(this.reason)
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                }, 0)
            } else {
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value)
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0)
                })

                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failCallback(this.reason)
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0)
                })
            }
        })
        return promise2
    }

    // 行为与调用.then(undefined, failCallback)相同
    catch(failCallback) {
        return this.then(undefined, failCallback)
    }

    // 1.不管是否成功都调用回调函数
    // 2.finally之后可以调用then，因此返回Promise对象
    // 3.通过.then()获取当前promise对象的状态
    finally(callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value)
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }

    /**静态方法 */
    // 1.all之后可以调用then，因此返回Promise对象
    // 2.内部可能存在异步任务，需要等待所有任务结束或抛出第一个异常
    static all(array) {
        let result = []
        let index = 0
        return new MyPromise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value
                index++
                if (index === array.length) {
                    resolve(result)
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i]
                if (current instanceof MyPromise) {
                    current.then(value => addData(i, value), reason => reject(reason))
                } else {
                    addData(i, current)
                }
            }

        })
    }

    // 1.返回原始数组中每个promise的执行结果
    // 2.执行结果为对象数组
    static allSettled(array) {
        let result = []
        let index = 0
        return new MyPromise((resolve, reject) => {
            function addData(key, value, status) {
                result[key] = {
                    status: status,
                    [status === FULFILLED ? 'value' : 'reason']: value
                }
                index++
                if (index === array.length) {
                    resolve(result)
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i]
                if (current instanceof MyPromise) {
                    current.then(value => addData(i, value, FULFILLED), reason => addData(i, reason, REJECTED))
                } else {
                    addData(i, current, FULFILLED)
                }
            }

        })
    }

    // 1.返回第一个成功状态的promise
    // 2.如果都失败，则返回失败的Promise
    static any(array) {
        return new MyPromise((resolve, reject) => {
            let index = 0
            for (let i = 0; i < array.length; i++) {
                let current = array[i]
                if (current instanceof MyPromise) {
                    current.then(value => resolve(value), reason => {
                        index++
                        if (index === array.length) {
                            reject(new Error('No Promise in Promise.any was resolved'))
                        }
                    })
                } else {
                    resolve(current)
                }
            }
            if (index === array.length) {
                reject(new Error('No Promise in Promise.any was resolved'))
            }
        })
    }

    // 1.返回第一个状态改变的promise
    static race(array) {
        return new MyPromise((resolve, reject) => {
            for (let i = 0; i < array.length; i++) {
                let current = array[i]
                if (current instanceof MyPromise) {
                    current.then(value => resolve(value), reason => reject(reason))
                } else {
                    resolve(current)
                }
            }
        })
    }

    // 1.resolve之后可以调用then，因此返回Promise对象
    static resolve(value) {
        if (value instanceof MyPromise) return value
        return new MyPromise(resolve => resolve(value))
    }

}

function resolvePromise(promise2, x, resolve, reject) {
    if (promise2 === x) {
        return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    }
    if (x instanceof MyPromise) {
        x.then(resolve, reject)
    } else {
        resolve(x)
    }
}

module.exports = MyPromise